package com.study.javaBasic.java_net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Name: ServerMainTest
 * @Description: java类作用描述
 * @Author: yn
 * @CreateDate: 2022/8/25 9:42
 * @Remark: 特殊说明
 * @Version: 1.0
 */
public class ServerMainTest {
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(6666); // 监听指定端口
		System.out.println("server is running...");
		for (;;) {
			Socket sock = ss.accept();
			//接收一个socket，会阻塞在handle方法
//			handle(sock);
			Thread t = new Thread(()->handle(sock));
			t.start();
		}
	}

	private static void handle(Socket sock){
		try {
			System.out.println(Thread.currentThread().getName()+" handle connection from " + sock.getRemoteSocketAddress());
			handle(sock.getInputStream(),sock.getOutputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static void handle(InputStream input, OutputStream output) throws IOException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
		BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
		writer.write("connected...\n");
		writer.flush();
		for (;;) {
			String s = reader.readLine();
			if (s.equals("bye")) {
				writer.write(Thread.currentThread().getName()+" bye\n");
				writer.flush();
				break;
			}
			writer.write(Thread.currentThread().getName()+" received: " + s + "\n");
			writer.flush();
		}
	}

}
